const path = require('path')

const {HotModuleReplacementPlugin} = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCSSExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')

module.exports = {
  // devtool: 'eval' 时不单独生成 sourcemap 文件，而是会放到 js 文件中
  // devtool: 'sourcemap' 时会生成 sourcemap 文件
  // devtool: 'inline-source-map' 时会将生成的 sourcemap 进行 base64 格式的编码放入 js 中
  devtool: 'inline-source-map',
  watch: true,
  entry: './src/main.js',
  output: {
    filename: 'bundle_[hash:8].js',
    path: path.resolve(__dirname, 'dist')
  },
  mode: 'production',
  module: {
    rules: [
      {
        test: /.(css|sass|scss)$/,
        use: [
          MiniCSSExtractPlugin.loader,
          'css-loader',
          {
            loader: 'px2rem-loader',
            options: {
              remUnit: 75,
              remPrecision: 8
            }
          },
          'sass-loader'
        ]
      },
      {
        test: /.(png|svg|jpg|jpeg|gif|webp)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: 'img/[name]-[hash:8].[ext]'
          }
        }
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    // new HotModuleReplacementPlugin(),
    new MiniCSSExtractPlugin({
      filename: '[name]_[contenthash:8].css'
    }),
    new OptimizeCSSAssetsWebpackPlugin({
      assetNameRegExp: /\.css$/g,
      cssProcessor: require('cssnano')
    }),
    new HtmlWebpackPlugin({
      title: '配置 sourcemap',
      template: 'index.html',
      minify: {
        html5: true,
        collapseWhitespace: true,
        preserveLineBreaks: false,
        minifyCSS: true,
        minifyJS: true,
        removeComments: true
      }
    })
  ]
}
